/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package theserver;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Emma
 */
public class ConnectedDevice implements Runnable {

    private Socket socket;
    private Controller controller;
    private ObjectOutputStream objectOutputStream;
    private ObjectInputStream objectInputStream;
    private Object inputStreamObject;
    private boolean threadRun;
    private Thread thread = new Thread(this);

    public ConnectedDevice(Socket socket, Controller controller) {
        this.socket = socket;
        this.controller = controller;

        thread.start();
        threadRun = true;

    }

    public void SendMessage(Object object) {
        try {
            objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
        } catch (IOException ex) {
            Logger.getLogger(ConnectedDevice.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {

            objectOutputStream.writeObject(object);
            objectOutputStream.flush();
        } catch (IOException ex) {
            Logger.getLogger(ConnectedDevice.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    public void run() {
        try {

            try {
                objectInputStream = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
            } catch (IOException ex) {
                Logger.getLogger(ConnectedDevice.class.getName()).log(Level.SEVERE, null, ex);
            }
            while (((inputStreamObject = objectInputStream.readObject()) != null) && threadRun) {
                if (inputStreamObject instanceof DeviceInfo) {
                    System.err.println("Tog emot");
                    DeviceInfo clm = (DeviceInfo) inputStreamObject;
                    int i = controller.checkIn(clm);
                    Integer integ = i;
                    //SendMessage(integ);
                    System.err.println("Skickat int");
                } else if (inputStreamObject instanceof String) {
                }
            }
            objectOutputStream.close();
            objectInputStream.close();
            socket.close();

        } catch (IOException ex) {
            Logger.getLogger(ConnectedDevice.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ConnectedDevice.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
